<template>
  <div class="PurchaseRecords">
    <!-- 顶部搜索区 -->
    <div class="PurchaseRecords-header">
      <div class="PurchaseRecords-header-search">
        <div class="PurchaseRecords-header-search-item">
          <div class="PurchaseRecords-header-search-item-label">编号</div>
          <el-input
              v-model="searchForm.orderNo"
              class="PurchaseRecords-header-search-item-input"
              placeholder="请输入采购单编号"
              clearable
          />
        </div>
        <div class="PurchaseRecords-header-search-item">
          <div class="PurchaseRecords-header-search-item-label">供应商</div>
          <el-input
              v-model="searchForm.supplierName"
              class="PurchaseRecords-header-search-item-input"
              placeholder="请输入供应商名"
              clearable
          />
        </div>
        <div class="PurchaseRecords-header-search-item">
          <div class="PurchaseRecords-header-search-item-label">日期范围</div>
          <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              unlink-panels
              :shortcuts="dateShortcuts"
              class="PurchaseRecords-header-search-item-input"
          />
        </div>
      </div>
      <div class="PurchaseRecords-header-btn">
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="PurchaseRecords-table">
      <el-table
          :data="tableData.list"
          v-loading="loading"
          class="PurchaseRecords-table-main"
          border
          stripe
      >
        <el-table-column type="index" :index="computeIndex" label="序号" width="80" align="center"/>
        <!-- 原 ID 列已移除，防止泄露真实 ID -->
        <el-table-column prop="orderNo" label="编号" width="140" align="center"/>
        <el-table-column prop="supplierName" label="供应商" min-width="160" align="center"/>
        <el-table-column prop="orderDate" label="日期" width="140" align="center"/>
        <el-table-column prop="totalAmount" label="合计金额(¥)" width="140" align="center">
          <template #default="{ row }">{{ formatMoney(row.totalAmount) }}</template>
        </el-table-column>
        <el-table-column prop="userName" label="最后操作用户" width="140" align="center"/>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="handleDetail(row)">详情</el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" :disabled="!row.canRed" @click="handleRed(row)">红冲</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="PurchaseRecords-pagination">
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="tableData.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="PurchaseRecords-pagination-main"
      />
    </div>

    <!-- 详情弹窗 -->
    <PurchaseOrderDetailDialog
        v-model:visible="detailVisible"
        :order-id="currentId"
    />
    <!-- 编辑弹窗 -->
    <PurchaseOrderEditDialog
        v-model:visible="editVisible"
        :order-id="currentId"
        @success="handleEditSuccess"
    />
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {listPurchaseOrders} from '../../../../api/purchaseOrderApi.js'
import {redPurchaseOrder} from "../../../../api/purchaseOrderApi.js";
import PurchaseOrderDetailDialog from './PurchaseOrderDetailDialog.vue'
import PurchaseOrderEditDialog from './PurchaseOrderEditDialog.vue'
import {ElMessage, ElMessageBox} from 'element-plus'

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  orderNo: '',
  supplierName: '',
  dateRange: [] // [startDate: Date, endDate: Date]
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近7天', value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 6);
      return [start, end]
    }
  },
  {
    text: '本月', value: () => {
      const d = new Date();
      const start = new Date(d.getFullYear(), d.getMonth(), 1);
      const end = new Date(d.getFullYear(), d.getMonth() + 1, 0);
      return [start, end]
    }
  }
]

// 获取本月起止日期
const getThisMonthRange = () => {
  const d = new Date();
  return [new Date(d.getFullYear(), d.getMonth(), 1), new Date(d.getFullYear(), d.getMonth() + 1, 0)]
}

// 分页
const pagination = ref({pageNum: 1, pageSize: 10})

// 表格数据
const tableData = ref({list: [], total: 0})

// 日期格式化 (后端 LocalDate 期望 yyyy-MM-dd)
const formatDate = (date) => {
  if (!date) return ''
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

// 加载数据（调用后端接口）
const loadData = async () => {
  loading.value = true
  try {
    const condition = {
      orderNo: searchForm.value.orderNo?.trim() || undefined,
      supplierName: searchForm.value.supplierName?.trim() || undefined
    }
    // 处理日期范围
    if (Array.isArray(searchForm.value.dateRange) && searchForm.value.dateRange.length === 2 && searchForm.value.dateRange[0] && searchForm.value.dateRange[1]) {
      condition.dateRange = [formatDate(new Date(searchForm.value.dateRange[0])), formatDate(new Date(searchForm.value.dateRange[1]))]
    }
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      condition
    }
    const res = await listPurchaseOrders(params)
    // PageInfo 结构：list, total
    tableData.value = {
      list: res.list || [],
      total: res.total || 0
    }
  } catch (e) {
    console.error('获取采购记录失败:', e)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.pageNum = 1;
  loadData()
}
// 重置（恢复默认本月）
const handleReset = () => {
  searchForm.value = {orderNo: '', supplierName: '', dateRange: getThisMonthRange()};
  pagination.value.pageNum = 1;
  loadData()
}
// 分页大小
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  pagination.value.pageNum = 1;
  loadData()
}
// 当前页
const handleCurrentChange = (val) => {
  pagination.value.pageNum = val;
  loadData()
}

// 弹窗状态
const detailVisible = ref(false)
const editVisible = ref(false)
const currentId = ref(null)

// 查看详情
const handleDetail = (row) => {
  currentId.value = row.id
  detailVisible.value = true
}
// 编辑
const handleEdit = (row) => {
  currentId.value = row.id
  editVisible.value = true
}
const reloadAfterEdit = () => {
  loadData()
}
// 新增：编辑成功回调（提示 + 刷新）
const handleEditSuccess = () => {
  ElMessage.success('采购单修改成功')
  reloadAfterEdit()
}
// 新增：红冲占位处理
const handleRed = (row) => {
  if (!row || !row.canRed) return
  ElMessageBox.confirm(`确认红冲采购单 ${row.orderNo} ?`, '确认红冲', {type: 'warning'})
      .then(async () => {
        await redPurchaseOrder(row.id).then(() => {
          ElMessage.success('采购单红冲成功')
          loadData()
        })
      })
}

// 金额格式化
const formatMoney = (v) => Number(v || 0).toFixed(2)

// 连续序号计算（跨分页）
const computeIndex = (i) => (pagination.value.pageNum - 1) * pagination.value.pageSize + i + 1

onMounted(() => {
  searchForm.value.dateRange = getThisMonthRange();
  loadData()
})
</script>

<style scoped lang="scss">
.PurchaseRecords {
  display: flex;
  flex-direction: column;
  height: 100%;

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 20px 0; // 与现有页面保持一致
    border-bottom: 1px solid #eee;

    &-search {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      align-items: center;
      justify-content: flex-start;
      gap: 16px;

      &-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        &-label {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          white-space: nowrap;
          width: 80px;
        }

        &-input {
          width: 200px;
        }
      }
    }

    &-btn {
      display: flex;
      align-items: center;
      flex: 0 0 200px;
      width: 200px;
      justify-content: flex-end;
      gap: 8px;
    }
  }

  &-table {
    flex: 1;
    padding: 16px 0;

    &-main {
      width: 100%;
    }
  }

  &-pagination {
    display: flex;
    justify-content: center;
    padding: 16px 0;
    border-top: 1px solid #eee;

    &-main {
      .el-pagination {
        justify-content: center;
      }
    }
  }
}
</style>
